/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.b2b.modules.fm.web.track;

import com.b2b.common.config.Global;
import com.b2b.common.mapper.JsonMapper;
import com.b2b.common.persistence.Page;
import com.b2b.common.typewrap.Dto;
import com.b2b.common.typewrap.Dtos;
import com.b2b.common.utils.DateUtils;
import com.b2b.common.utils.MyBeanUtils;
import com.b2b.common.utils.SpringContextHolder;
import com.b2b.common.utils.StringUtils;
import com.b2b.common.utils.excel.ExportExcel;
import com.b2b.common.utils.excel.ImportExcel;
import com.b2b.common.web.BaseController;
import com.b2b.modules.fm.assets.FmConsts;
import com.b2b.modules.fm.assets.FmUtils;
import com.b2b.modules.fm.dao.base.FmEquipmentDao;
import com.b2b.modules.fm.dao.track.FmStoreCatDao;
import com.b2b.modules.fm.entity.base.FmEquipment;
import com.b2b.modules.fm.entity.base.FmStore;
import com.b2b.modules.fm.entity.track.FmEqualarm;
import com.b2b.modules.fm.entity.track.FmStoreCat;
import com.b2b.modules.fm.service.base.FmEquipmentService;
import com.b2b.modules.fm.service.base.FmStoreService;
import com.b2b.modules.fm.service.track.FmEqualarmService;
import com.b2b.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *  门店监测信息  Controller
 * @author soldier lee
 * @version 2016-11-20
 */
@Controller
@RequestMapping(value = "${adminPath}/fm/track/fmStoreCat")
public class FmStoreCatController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(FmStoreCatController.class);
	private FmStoreCatDao fmStoreCatDao = SpringContextHolder.getBean(FmStoreCatDao.class);
	/**
	 * 门店 实时监控 全景图 画面
	 *  门店实时信息、设备的实时信息
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = {"list", ""})
	public String list(@RequestParam(required = true) String sto002,HttpServletRequest request, HttpServletResponse response, Model model) {
        this.logger.debug(FmConsts.LOG_FLAG_OUT_PREFIX+"当前监控跟踪门店编号："+sto002);
		FmStoreService fmStoreService = SpringContextHolder.getBean(FmStoreService.class);
		FmStore fmStore = fmStoreService.findUniqueByProperty("sto002",sto002);

		FmEquipmentDao fmEquipmentDao =SpringContextHolder.getBean(FmEquipmentDao.class);
		Dto params = Dtos.newDto();
		if (!UserUtils.isAdmin())	params.put("equ000",Global.SHOW);
		params.put("equ013",sto002);
		List<FmEquipment> fmEquipmentList =  fmEquipmentDao.getAllByStoreNo(params);
		model.addAttribute("fmStore",fmStore).addAttribute("fmEquipmentList",fmEquipmentList);
		return "modules/fm/track/fmStoreCat";
	}


	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "getStoreIndexByNo")
	public Dto getStoreIndexByNo(@RequestParam(required = true) String mno,@RequestParam(required = true) String dno,HttpServletRequest request, HttpServletResponse response, Model model) {
		Dto outDto = Dtos.newOutDto();
		Dto inDto = Dtos.newDto(request);

		// 当前温度
		Dto currTem = fmStoreCatDao.getCurrTemByNo(inDto);
		if (StringUtils.isNotEmpty(currTem)){
			outDto.put("currTem",currTem.getDouble("tem006") == null?0d:currTem.getDouble("tem006"));
			Date lastUpdateTime = currTem.getDate("tem003");
			String updateTime = "-";//未获取到数据情况
			if (StringUtils.isNotEmpty(lastUpdateTime)){
				updateTime = DateUtils.formatDate(lastUpdateTime,DateUtils.HHMMSS);
			}
			outDto.put("updateTime",updateTime);
		}
		Double todayMaxElec = fmStoreCatDao.getTodayMaxElecByNo(inDto);
		Double todayMinElec = fmStoreCatDao.getTodayMinElecByNo(inDto);
		Double todayCurrElec = (todayMaxElec==null?0:todayMaxElec) - (todayMinElec==null?0:todayMinElec);
		outDto.put("todayCurrElec",todayCurrElec == null?0d:todayCurrElec);
		return outDto;
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "getDeviceIndex")
	public Dto getDeviceIndex(HttpServletRequest request, HttpServletResponse response, Model model) {
		Dto outDto = Dtos.newOutDto();
		Dto inDto = Dtos.newDto(request);
		String dnos = inDto.getString("dnos");
		String mno = inDto.getString("mno");

		List<Dto> rtList = new ArrayList<>();
		for (String dno : dnos.split(",")){
			inDto.put("dno",dno);
			// 当前温度
			Dto currTem = fmStoreCatDao.getCurrTemByNo(inDto);
			if (StringUtils.isNotEmpty(currTem)) {
				currTem.put("dno", dno);
				currTem.put("updateTime", DateUtils.formatDateTime(currTem.getDate("tem003")));
				rtList.add(currTem);
			}
		}
		outDto.put("rtList",rtList);
		return outDto;
	}

	/**
	 * 门店的温度监测画面
	 * @param sto005
	 * @param request
	 * @param response
	 * @param model
     * @return
     */
	@RequiresPermissions("user")
	@RequestMapping("catStoreTemLine")
	public String catStoreTemLine(@RequestParam(required = true) String sto005,@RequestParam(required = true) String equ001,
								  @RequestParam String equ002,HttpServletRequest request, HttpServletResponse response, Model model) {
		this.logger.debug(FmConsts.LOG_FLAG_OUT_PREFIX+"当前监控跟踪主机号："+sto005);
		Calendar calendar = Calendar.getInstance();
        String endtime = DateUtils.formatDateTime(calendar.getTime());//截至到当前时间
		calendar.add(Calendar.HOUR_OF_DAY,-24);
		String starttime = DateUtils.formatDateTime(calendar.getTime());//1天时间内 获取
		String dno = equ001;//门店温度指标默认取设备编号为1的采集值  modify 调整为动态传参 便于设备监控温度复用

		Dto params = Dtos.newDto();
		params.put("mno",sto005);
		params.put("dno",dno);
		//获取针对设备的 标准温度和允许温差
		Dto referenceLine = FmUtils.getTemReferenceLineData(params);

		params.put("starttime",starttime);
		params.put("endtime",endtime);
		params.put("cnt",10);//默认前10笔
		List<Dto> temList = this.fmStoreCatDao.getTopCurrTemByNo(params);
		String lasttime = "";//获取第一次的最后更新时间
		if (temList!=null && temList.size()>0) {
			lasttime =  DateUtils.formatDateTime(temList.get(0).getDate("tem003"));
		}
		List<String> aixData = new ArrayList<>();
		List<Double> yData = new ArrayList<>();
		for (Dto dto : temList){
			aixData.add(DateUtils.formatDateTime(dto.getDate("tem003")));
			yData.add(dto.getDouble("tem006"));
		}
		Dto chartData = Dtos.newDto();
		chartData.put("aixs",aixData);
		chartData.put("series",yData);
		model.addAttribute("sto005",sto005).addAttribute("lasttime",lasttime).addAttribute("chartData", JsonMapper.toJsonString(chartData))
		.addAttribute("starttime",starttime).addAttribute("endtime",endtime).addAttribute("equ001",equ001).addAttribute("refLine",referenceLine).addAttribute("equ002",equ002);
		return "modules/fm/track/catStoreTemLine";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "getStoreTemLineData")
	public Dto getStoreTemLineData(HttpServletRequest request, HttpServletResponse response, Model model) {
		Dto outDto = Dtos.newOutDto();
		Dto inDto = Dtos.newDto(request);
		Dto curr = fmStoreCatDao.getCurrTemByNo(inDto);
		//获取针对设备的 标准温度和允许温差
		Dto referenceLine = FmUtils.getTemReferenceLineData(inDto);
		if (StringUtils.isNotEmpty(curr)){
			double temp = curr.getDouble("tem006") == null?0d:curr.getDouble("tem006");
			outDto.put("currTem",temp+referenceLine.getDouble("customTem"));
			Date lastUpdateTime = curr.getDate("tem003");
			String updateTime = "-";//未获取到数据情况
			if (StringUtils.isNotEmpty(lastUpdateTime)){
				updateTime = DateUtils.formatDateTime(lastUpdateTime);
			}
			outDto.put("updateTime",updateTime);
		}
		return outDto;
	}
	@RequiresPermissions("user")
	@RequestMapping("catStoreElecLine")
	public String catStoreElecLine(@RequestParam(required = true) String sto005,HttpServletRequest request, HttpServletResponse response, Model model) {
		this.logger.debug(FmConsts.LOG_FLAG_OUT_PREFIX+"当前监控跟踪主机号："+sto005);
		Calendar calendar = Calendar.getInstance();
		String endtime = DateUtils.formatDateTime(calendar.getTime());//截至到当前时间
		calendar.add(Calendar.HOUR_OF_DAY,-24);
		String starttime = DateUtils.formatDateTime(calendar.getTime());//1天时间内 获取
		Dto params = Dtos.newDto();
		params.put("mno",sto005);
		params.put("starttime",starttime);
		params.put("endtime",endtime);
		params.put("cnt",10);//默认前10笔
		List<Dto> elecList = this.fmStoreCatDao.getTopCurrElecByNo(params);
		String lasttime = "";//获取第一次的最后更新时间
		if (elecList!=null && elecList.size()>0) {
			lasttime =  DateUtils.formatDateTime(elecList.get(0).getDate("ele002"));
		}
		List<String> aixData = new ArrayList<>();
		List<Double> yData = new ArrayList<>();
		Double todayMinElec = fmStoreCatDao.getTodayMinElecByNo(params);
		for (Dto dto : elecList){
			aixData.add(DateUtils.formatDate(dto.getDate("ele002"), DateUtils.HHMM));
			yData.add(dto.getDouble("ele005")-todayMinElec);
		}
		Dto chartData = Dtos.newDto();
		chartData.put("aixs",aixData);
		chartData.put("series",yData);
		model.addAttribute("sto005",sto005).addAttribute("lasttime",lasttime).addAttribute("chartData", JsonMapper.toJsonString(chartData))
				.addAttribute("starttime",starttime).addAttribute("endtime",endtime);
		return "modules/fm/track/catStoreElecLine";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "getStoreElecLineData")
	public Dto getStoreElecLineData(HttpServletRequest request, HttpServletResponse response, Model model) {
		Dto outDto = Dtos.newOutDto();
		Dto inDto = Dtos.newDto(request);
		Dto curr = fmStoreCatDao.getCurrElecByNo(inDto);
		Double todayMinElec = fmStoreCatDao.getTodayMinElecByNo(inDto);
		if (StringUtils.isNotEmpty(curr)){
			Double et = curr.getDouble("ele005") == null?0d:curr.getDouble("ele005");
			outDto.put("currTem",et-todayMinElec);
			Date lastUpdateTime = curr.getDate("ele002");
			String updateTime = "-";//未获取到数据情况
			if (StringUtils.isNotEmpty(lastUpdateTime)){
				updateTime = DateUtils.formatDateTime(lastUpdateTime);
			}
			outDto.put("updateTime",updateTime);
			outDto.put("aixData",DateUtils.formatDate(lastUpdateTime,DateUtils.HHMM));
		}
		return outDto;
	}

	/**
	 * 门店电量按照月度汇总
	 * @param sto005
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("user")
	@RequestMapping("catStoreElecBar")
	public String catStoreElecBar(@RequestParam(required = true) String sto005,HttpServletRequest request, HttpServletResponse response, Model model) {
		this.logger.debug(FmConsts.LOG_FLAG_OUT_PREFIX+"当前监控跟踪主机号："+sto005);
		Calendar calendar = Calendar.getInstance();
		String endtime = DateUtils.formatDate(calendar.getTime());//截至到当前时间
		calendar.set(Calendar.DAY_OF_MONTH,1);
		String starttime = DateUtils.formatDate(calendar.getTime());//当前月份1号开始
		Dto params = Dtos.newDto();
		params.put("mno",sto005);
		params.put("starttime",starttime);
		params.put("endtime",endtime);
		params.put("cnt",10);//默认前10笔
		List<Dto> elecList = this.fmStoreCatDao.getTopCurrElecByNo(params);
		String lasttime = "";//获取第一次的最后更新时间
		if (elecList!=null && elecList.size()>0) {
			lasttime =  DateUtils.formatDateTime(elecList.get(0).getDate("ele002"));
		}
		List<String> aixData = new ArrayList<>();
		List<Double> yData = new ArrayList<>();
		Double todayMinElec = fmStoreCatDao.getTodayMinElecByNo(params);
		for (Dto dto : elecList){
			aixData.add(DateUtils.formatDateTime(dto.getDate("ele002")));
			yData.add(dto.getDouble("ele005")-todayMinElec);
		}
		Dto chartData = Dtos.newDto();
		chartData.put("aixs",aixData);
		chartData.put("series",yData);
		model.addAttribute("sto005",sto005).addAttribute("lasttime",lasttime).addAttribute("chartData", JsonMapper.toJsonString(chartData))
				.addAttribute("starttime",starttime).addAttribute("endtime",endtime);
		return "modules/fm/track/catStoreElecLine";
	}
}